<template>
    <div class="modal-overlay" v-if="open">
        <div class="modal_1" v-if="!isFinished">
            <div class="aiVoiceMain" v-if="!isFinished">
                <button class="close-btn" @click="onClose"><Close /></button>
                <div class="top-title">AI语音病历</div>
                <div class="info-bubble"><span style="padding-top: 8px;">医生专注沟通，AI精准记录</span></div>
                <div class="mic-container"></div>
                <div class="audio-wave" v-if="isRecording && !isPaused">
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                    <div class="wave-bar"></div>
                </div>
                <div class="audio-wave-stop" v-else></div>
                <div class="time-display"> {{ isRecording ? formattedTime : '' }}</div>
                <div class="button-container">
                    <!-- 开始按钮 -->
                    <button class="btn start-btn" v-if="!isRecording" @click="startRecording" >
                        <i class="his-icon icon-mic-on-full"></i>&nbsp;开&nbsp;始
                    </button>
                    <button class="btn pause-btn" v-if="isRecording" @click="togglePause">
                        <template v-if="isPaused">
                            <i class="his-icon icon-start"></i>&nbsp;继&nbsp;续
                        </template>
                        <template v-else>
                            <i class="his-icon icon-pause"></i>&nbsp;暂&nbsp;停
                        </template>
                    </button>
                    <button class="btn stop-btn" v-if="isRecording" @click="stopRecording">
                        <i class="his-icon icon-stop"></i>&nbsp;结&nbsp;束
                    </button>
                </div>
                <div class="hint-text">{{isRecording ? '普通话效果最佳哦！':''}}</div>
            </div>
        </div>
        <div class="modal_2" v-if="isFinished && isGenerate">
            <div class="container" v-if="isFinished">
                <button class="close-btn" @click="onClose"><Close /></button>
                <div class="progress-bar">
                    <div class="icon"></div>
                    <div class="text">AI语音病历</div>
                </div>
                <div class="content">
                    <div class="section">
                        <div class="section-title">语音内容：</div>
                        <div class="voice-content">
                            {{emrData.text}}
                        </div>
                    </div>
                    
                    <div v-if="type == 'mz'" class="section">
                        <div class="section-title">主诉：</div>
                        <!-- <textarea class="input-field" placeholder="" spellcheck="false">{{emrData.zs}}</textarea> -->
                        <el-input type="textarea" class="input-field" :autosize="{ minRows: 1, maxRows: 3 }" 
                            v-model="emrData.zs">
                        </el-input>
                    </div>
                    
                    <div v-if="type == 'mz'" class="section">
                        <div class="section-title">现病史：</div>
                        <!-- <textarea class="input-field multi-line" placeholder="" spellcheck="false">{{emrData.xbs}}</textarea> -->
                        <el-input type="textarea" class="input-field" :autosize="{ minRows: 2, maxRows: 3 }" 
                            v-model="emrData.xbs">
                        </el-input>
                    </div>
                    
                    <div v-if="type == 'mz'" class="section">
                        <div class="section-title">既往史：</div>
                        <el-input type="textarea" class="input-field" :autosize="{ minRows: 2, maxRows: 3 }" 
                            v-model="emrData.jws">
                        </el-input>
                        <!-- <textarea class="input-field" placeholder="" spellcheck="false">{{emrData.jws}}</textarea> -->
                    </div>

                    <div v-if="type == 'zy'" class="section">
                        <div class="section-title">导入内容：</div>
                        <el-input type="textarea" class="input-field" :autosize="{ minRows: 8, maxRows: 15 }" 
                            v-model="emrData.content">
                        </el-input>
                    </div>
                </div>
                <div class="footer">
                    <button class="reference-btn"  @click="useAIEmrData" >引用</button>
                </div>
            </div>
        </div>
        <div class="modal_loading" v-if="isFinished && !isGenerate">
          <button class="close-btn" @click="onClose"><Close /></button>
          <div class="title">
            <div class="icon"></div>
            <div class="text">AI语音病历</div>
          </div>
          <div class="content">AI正在总结病历，请稍候...</div>
          <div class="bubble">不要着急哦~</div>
          <div class="robot"></div>
        </div>
    </div>
</template>

<script>
    import Recorder from 'recorder-core';
    import 'recorder-core/src/engine/wav';
    import {invokeAi} from '../api/aiUtil';
    export default {
        data() {
            return {
                open:true,
                isRecording:false,  //是否开始录音
                isPaused: false,   //是否暂停
                recordingTime: 0, //计时
                isFinished:false,  //是否完成录音
                isGenerate:false,  //是否生成主诉现病史
                emrData:{
                },
            }
        },
        beforeDestroy() {
            // 清理资源
            if (this.timer) {
                clearInterval(this.timer);
            }
            if (this.recorder) {
                this.recorder.stop();
            }
        },
        computed: {
            formattedTime() {
                const minutes = Math.floor(this.recordingTime / 60);
                const seconds = Math.floor(this.recordingTime % 60);
                return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            },
        },
        methods: {
            show(type){
                this.openRecording();
                this.type = type;
                this.recordingTime = 0;
                this.open = true;
                this.isRecording = false;
                this.isPaused = false;
                this.isFinished = false;
                this.isGenerate = false;

            },
            openRecording(){
                //创建录音对象
                this.recorder = Recorder({
                    type: 'wav', //录音格式，可以换成wav等其他格式
                    sampleRate: 16000, //录音的采样率，越大细节越丰富越细腻
                    bitRate: 16, //录音的比特率，越大音质越好
                    onProcess: (
                    buffers,
                    powerLevel,
                    bufferDuration,
                    bufferSampleRate,
                    newBufferIdx,
                    asyncEnd,
                    ) => {
                        console.log(bufferDuration+""+newBufferIdx+""+asyncEnd);
                        //录音实时回调，大约1秒调用12次本回调
                        //可实时绘制波形，实时上传（发送）数据
                        if (this.wave) {
                            this.wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate);
                        }
                    },
                });
                if (!this.recorder) {
                    alert('当前浏览器不支持录音功能！');
                    return;
                }
                //打开录音，获得权限
                this.recorder.open(
                    () => {
                    console.log('录音已打开');
                    if (this.$refs.recwave) {
                        //创建音频可视化图形绘制对象
                        this.wave = Recorder.WaveView({ elem: this.$refs.recwave });
                    }
                    },
                    (msg, isUserNotAllow) => {
                        //用户拒绝了录音权限，或者浏览器不支持录音
                        console.log((isUserNotAllow ? 'UserNotAllow，' : '') + '无法录音:' + msg);
                    },
                );
            },
            async startRecording() {
                try {
                    this.isRecording = true;
                    this.isPaused = false;
                    this.recordingTime = 0;
                    // 开始录制
                    this.recorder.start();

                    // 开始计时
                    this.timer = setInterval(() => {
                    //如果暂停时间不增长
                    if(this.isPaused){
                        return;
                    }
                    this.recordingTime++;
                    }, 1000);
                    // 实时更新波形
                    // this.recorder.onAudioProcess = (audioBuffer) => {
                    // this.wavesurfer.empty();
                    // this.wavesurfer.loadDecodedBuffer(audioBuffer);
                    // };
                } catch (error) {
                    console.error('Error accessing microphone:', error);
                }
            },
            //暂停
            togglePause() {
                if (this.isPaused) {
                    this.recorder.resume();
                } else {
                    //暂停
                    this.recorder.pause();
                }
                this.isPaused = !this.isPaused;
            },
            // 停止录制
            stopRecording() {
                this.isRecording = false;
                clearInterval(this.timer);
                this.recorder.stop(
                    (blob, duration) => {
                        console.log(duration);
                    //blob就是我们要的录音文件对象，可以上传，或者本地播放
                    this.audioBlob = blob;
                    const file = new File([blob], 'audio.wav');
                    const formData = new FormData();
                    formData.append('file', file);
                    formData.append('type', this.type);  //类型 mz或zy
                    formData.append('user',"admin"); //getStore({ name: 'userInfo' }).user_name
                    var param = {
                        formData: formData,
                        type:"getVoice",
                    }
                    //this.downloadAudio();
                    this.recorder.close(); //关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
                    this.recorder = null;
                    this.isFinished = true;
                    //调用AI接口返回文字
                    invokeAi(param,this.showTextByVoice);
                    },
                    (err) => {
                        console.error('结束录音出错：' + err);
                        this.recorder.close(); //关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
                        this.recorder = null;
                    },
                );
            },
            //显示文字
            showTextByVoice(data,paramData){
                if(paramData.success){
                    this.emrData.zs = "";
                    this.emrData.xbs = "";
                    this.emrData.jws = "";
                    if(this.type == 'mz'){
                        this.emrData.text = data.text;
                        if(data.result){
                            var content = data.result;
                            content = content.replace(/<think>.*?<\/think>/gs, "");
                            content = content.replace(/\s+/g, "");
                            content = content.replace("```json", "");
                            content = content.replace("```", "");
                            var info = JSON.parse(content);
                            this.emrData.zs = info.zs == "无" ? "" : info.zs;
                            this.emrData.xbs = info.xbs == "无" ? "" : info.xbs;
                            this.emrData.jws = info.jws == "无" ? "" : info.jws;
                        }
                    }
                    else if(this.type == 'zy'){
                        this.emrData.text = data.text;
                        if(data.result){
                            content = data.result;
                            content = content.replace(/<think>.*?<\/think>/gs, "");
                            content = content.replace(/\s+/g, "");
                            content = content.replace("```json", "");
                            content = content.replace("```", "");
                            info = JSON.parse(content);
                            this.emrData.content = info.content == "无" ? "" : info.content;
                        }
                    }
                    this.isGenerate = true;
                }else{
                    this.$message.warning(data);
                }
            },
            onClose(){
                this.isRecording = false;
                clearInterval(this.timer);
                if(this.recorder){
                    this.recorder.close();
                }
                this.open = false;
            },
                //引用AI数据
            useAIEmrData(){
              this.$emit('useAIEmrData',this.emrData);
              this.open = false;
            }
        }
    }
</script>

<style scoped>
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            opacity: 1;
            transition: opacity 0.3s;
        }

        .modal_1 {
            height: 540px;
            width: 400px;
            background-image: url("/img/his/aivoice-bg.png"); 
            background-size: cover;
            border-radius: 10px;
            box-shadow: 0 5px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            transform: translateY(0);
            transition: transform 0.3s;
        }

        .modal_2 {
            min-height: 710px;
            max-height: 800px;
            width: 600px;
            border-radius: 10px;
            overflow: hidden;
            transform: translateY(0);
            transition: transform 0.3s;
        }

        .aiVoiceMain {
            height: 100%;
            width: 100%;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            position: relative;
            overflow: hidden;
        }
        
        /* 关闭按钮 */
        .close-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 20px;
            height: 20px;
            background: none;
            border: none;
            font-size: 20px;
            color: #999;
            cursor: pointer;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: color 0.3s;
        }
        
        .close-btn:hover {
            background-color: #f1f1f1;
            color: #999;
        }
        
        /* 标题 */
        .top-title {
            padding-top: 20px;
            height: 33px;
            font-family: 微软雅黑;
            font-weight: 500;
            font-size: 22px;
            color: #333333;
            letter-spacing: 3px;
            text-align: left;
            font-style: normal;
            text-transform: none;
        }

        /* 说明标签 */
        .info-bubble {
            margin-top: 20px;
            width: 230px;
            height: 50px;
            background-image: url("/img/his/aivoice-bubble.png");
            background-size: cover;
            color: white;
            padding: 10px 15px 20px 15px;
            font-size: 16px;
            display: flex;
            justify-content: center;
        }
        
        /* 麦克风容器 */
        .mic-container {
            margin-top: -10px;
            width: 176px;
            height: 164px;
            background-image: url("/img/his/aivoice-mic.png");
            background-size: cover;
        }
        
        
        /* 音频波形 */
        .audio-wave-stop {
            margin-top: 20px;
            width: 98px;
            height: 27px;
            background-image: url("/img/his/aivoice-wave-stop.png");
            background-size: cover;
        }

        .audio-wave {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 3px;
            margin-top: 20px;
            width: 98px;
            height: 27px;
        }
        
        .wave-bar {
            width: 3px;
            background-color: #90caf9;
            border-radius: 3px;
            animation: wave 1.5s infinite ease-in-out;
        }
        .wave-bar:nth-child(1) { height: 10px; animation-delay: 0s; }
        .wave-bar:nth-child(2) { height: 15px; animation-delay: 0.1s; }
        .wave-bar:nth-child(3) { height: 8px; animation-delay: 0.2s; }
        .wave-bar:nth-child(4) { height: 20px; animation-delay: 0.3s; }
        .wave-bar:nth-child(5) { height: 12px; animation-delay: 0.4s; }
        .wave-bar:nth-child(6) { height: 18px; animation-delay: 0.5s; }
        .wave-bar:nth-child(7) { height: 5px; animation-delay: 0.6s; }
        .wave-bar:nth-child(8) { height: 14px; animation-delay: 0.7s; }
        .wave-bar:nth-child(9) { height: 10px; animation-delay: 0.8s; }
        .wave-bar:nth-child(10) { height: 16px; animation-delay: 0.9s; }
        .wave-bar:nth-child(11) { height: 7px; animation-delay: 1.0s; }
        .wave-bar:nth-child(12) { height: 19px; animation-delay: 1.1s; }
        .wave-bar:nth-child(13) { height: 11px; animation-delay: 1.2s; }

        @keyframes wave {
            0%, 100% { transform: scaleY(1); }
            50% { transform: scaleY(0.5); }
        }
        
        /* 时间显示 */
        .time-display {
            padding-top: 25px;
            width: 45px;
            height: 20px;
            font-family: Arial, Arial;
            font-weight: 400;
            font-size: 18px;
            color: #333333;
            line-height: 33px;
            text-align: left;
            font-style: normal;
            text-transform: none;
        }
        
        /* 按钮容器 */
        .button-container {
            padding-top: 20px;
            display: flex;
            gap: 20px;
            width: 100%;
            max-width: 400px;
            justify-content: center;
        }
        
        /* 按钮样式 */
        .btn {
            padding: 10px 10px;
            border-radius: 30px;
            font-size: 18px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            border: none;
            min-width: 120px;
        }

        .start-btn {
            width: 160px;
            height: 50px;
            background-color: white;
            color: #42a5f5;
            border: 1px solid #42a5f5;
        }
        
        .start-btn:hover {
            background-color: #2196f3;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(59, 130, 246, 0.2);
        }
        
        .pause-btn {
            background-color: white;
            color: #E6A23C;
            border: 1px solid #E6A23C;
        }
        
        .pause-btn:hover {
            background-color: #FFFBF0;
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(230, 162, 60, 0.1);
        }
        
        .stop-btn {
            background-color: #FF0304;
            color: white;
        }
        
        .stop-btn:hover {
            background-color: #d32f2f;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(244, 67, 54, 0.3);
        }
        
        /* 底部提示 */
        .hint-text {
            margin-top:15px;
            font-family: Source Han Sans SC, Source Han Sans SC;
            font-weight: 400;
            font-size: 14px;
            color: #999999;
            letter-spacing: 1px;
            text-align: left;
            font-style: normal;
            text-transform: none;
        }
        
        /* 响应式设计 */
        @media (max-width: 480px) {
            .button-container {
                flex-direction: column;
                align-items: center;
            }
            
            .btn {
                width: 80%;
            }
            
            h1 {
                font-size: 24px;
            }
            
            .mic-container {
                width: 160px;
                height: 160px;
            }
        }


        .container {
            width: 100%;
            box-sizing: border-box;
            padding: 20px;
            background: linear-gradient( 0deg, #DEEAFF 0%, #DEEAFF 0%, #DFEBFF 0%, #FFFFFF 100%);
            border-radius: 10px;
        }
        
        .progress-bar {
            width: 100%;
            height: 60px;
            border-radius: 10px;
            background: linear-gradient(
                90deg, 
                rgba(62, 146, 255, 0.2) 0%,   /* 带透明度的#3E92FF */
                rgba(84, 151, 252, 0.2) 17%,  /* 带透明度的#5497FC */
                rgba(192, 176, 235, 0.2) 100% /* 带透明度的#C0B0EB */
            );
            display: flex;
            align-items: center;
        }
        
        .progress-bar .icon {
            margin-left: 20px;
            width: 16px;
            height: 15px;
            background-image: url("/img/his/aivoice-progress-icon.png");
            background-size: cover;
        }
        
        .progress-bar .text {
            margin-left: 10px;
            font-family: 微软雅黑;
            font-weight: 500;
            font-size: 18px;
            color: #333333;
            text-align: left;
            font-style: normal;
            text-transform: none;
            letter-spacing: 2px;
        }
        
        .content {
            padding-top: 10px;
        }
        
        .section {
            width: 100%;
            box-sizing: border-box;
            background: #FFFFFF;
            border-radius: 10px 10px 10px 10px;
            padding: 10px;
            margin-bottom: 10px;
        }
        
        .section-title {
            font-size: 16px;
            font-family: 微软雅黑;
            font-weight: 500;
            color: #333333;
            margin-bottom: 10px;
        }
        
        .voice-content {
            width: 100%;
            min-height: 40px;
            max-height: 140px;
            overflow-x: hidden;
            overflow-y: auto;
            background: #EFF6FF;
            border-radius: 6px;
            box-sizing: border-box;
            padding: 10px;
            font-family: Source Han Sans SC, Source Han Sans SC;
            font-weight: 400;
            font-size: 14px;
            color: #666666;
            text-align: left;
            font-style: normal;
            text-transform: none;
        }
        
        .input-field {
            box-sizing: border-box;
            border-radius: 5px;
            border: 1px solid #DCDFE6;
            padding: 10px;
        }
        
        .footer {
            padding-top: 10px;
            border-top: 1px solid #e5e7eb;
            display: flex;
            justify-content: center;
        }
        
        .reference-btn {
            width: 160px;
            height: 45px;
            background: #409EFF;
            border-radius: 44px;
            color: white;
            border: none;
            font-family: Source Han Sans SC, Source Han Sans SC;
            font-weight: 400;
            font-size: 18px;
        }
        
        .reference-btn:hover {
            background-color: #3182ce;
        }
        
        .reference-btn:active {
            background-color: #2b6cb0;
        }

        .modal_loading {
            width: 400px;
            height: 300px;
            box-sizing: border-box;
            padding: 20px;
            background: linear-gradient( 180deg, #E0EDFF 0%, #F0EAFF 100%);
            border-radius: 10px;
            box-shadow: 0 5px 30px rgba(0, 0, 0, 0.2);
            transform: translateY(0);
            transition: transform 0.3s;
            overflow-y: auto;
        }

        .modal_loading .title{
            width: 100%;
            height: 25px;
            display: flex;
            align-items: center;
        }

        .modal_loading .title .icon{
            width: 16px;
            height: 15px;
            background-image: url("/img/his/aivoice-progress-icon.png");
            background-size: cover;
        }

        .modal_loading .title .text{
            margin-left: 10px;
            font-family: Source Han Sans SC, Source Han Sans SC;
            font-weight: 500;
            font-size: 18px;
            color: #333333;
            text-align: left;
            font-style: normal;
            text-transform: none;
            letter-spacing: 1px;
        }

        .modal_loading .content{
            width: 100%;
            height: 110px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: Source Han Sans SC, Source Han Sans SC;
            font-weight: 500;
            font-size: 28px;
            color: #000000;
        }

        .modal_loading .bubble{
            width: 132px;
            height: 51px;
            box-sizing: border-box;
            margin-left: 114px;
            background-image: url("/img/his/aidiag-bubble.png");
            background-size: cover;
            font-size: 16px;
            color: #2C5BF6;
            padding-top:10px;
            padding-left:20px;
            letter-spacing: 2px;
            animation: breathe 2s infinite ease-in-out; /* 呼吸动画，2秒一次，无限循环，缓入缓出 */
        }

        .modal_loading .robot{
            width: 61px;
            height: 61px;
            margin-left: 134px;
            background-image: url("/img/his/aidiag-robot.png");
            background-size: cover;
            animation: breathe 2s infinite ease-in-out; /* 呼吸动画，2秒一次，无限循环，缓入缓出 */
        }
        
        @keyframes breathe {
            0%, 100% {
                transform: scale(1); /* 初始和结束时大小为1倍 */
            }
            50% {
                transform: scale(1.1); /* 中间时放大到1.1倍 */
            }
        }
</style>

<style lang="scss" scoped>

    :deep(.el-textarea__inner) {
        background-color: rgba(255, 255, 255, 0);
        border: 0px solid #fff;
        box-shadow: none;
        resize: none;
        padding: 0px;
        word-wrap: break-word;
        word-break: break-all;
        color: #666666;
        letter-spacing: 1px;
    }
</style>